<!-- Discuss_TeacherEdit.html -->
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>
     <meta name="format-detection" content="telephone=no, email=no, date=no, address=no">
    <title>教师端编辑讨论页</title>
    <link rel="stylesheet" href="../../css/weui.min.css">
    <link rel="stylesheet" href="../../css/mui.min.css">
    <link rel="stylesheet" href="../../css/base.css">
    <style type="text/css">
        body{
            background-color: white;
        }
    	.nav-item{
    		text-align: center;
    		text-decoration:none;
    	}
    	.mui-input-group .mui-input-row {
            height: 40px;
        }
        .head_div {
            background: #F0F0F0;
            height: 30px;
        }
        .head_div span {
            padding: 5px 10px;
        }
        input[type=color], input[type=date], input[type=datetime-local], input[type=datetime], input[type=email], input[type=month], input[type=number], input[type=password], input[type=search], input[type=tel], input[type=text], input[type=time], input[type=url], input[type=week], select, textarea {
            line-height: 30px;
            width: 100%;
        }
        .stuname {
            padding: 11px 0;
            line-height: 2.1;
        }
        .padding_left_10 {
            padding-left: 10px;
        }
        .padding_right_10 {
            padding-right: 10px;
        }
        .bottom_15 {
            padding-bottom: 15px;
        }
        .bottom_0_position {
            position: absolute;
            bottom: 5px;
            right: 10px;
        }
        .height50 {
            height: 50px;
            line-height: 50px;
        }
        .add_pic_span {
            text-align: center;
            width: 100%;
        }
        .selected-image{
            padding: 10px;
            text-align: center;
        }
        .img_pic_style {
            max-width: 100%;
            /*width: 100%;*/
        }
        .img-del{
            position: absolute;
            right: 0;
            top: 330px;
            width: 20px;
        }
        .textarea_t{
            height: 130px;
            line-height: 1.4em;
        }
        .select-class-cell{
            padding: 10px;
        }
        .select-class-title{
            margin-right: 20px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .name-input[type=text]{
            padding: 10px;
        }
        .nav-item:active{
            color: #fff;
        }
    </style>
</head>
<body>
    <div class="base_style_color " id='BarAppearance' style="height: 22px;width: 100%"></div>
    <div class="base_navigation_bar base_style_color base_navigation_item_bar">
        <a class="base_left_item nav-item" href="#" onclick="backClick()">
            取消
        </a>
        <span>创建讨论</span>
    	<a id="pub_btn" class="base_right_item nav-item" href="#" onclick="saveClick()">
            保存
        </a>
    </div>
    <div class="base_content_div">
	    <form class="  mui-input-group">
            <div class="head_div" >
                <span class="base_content_font base_dark_grey" >讨论名称</span>
            </div>
            <div class="mui-input-row" >
                <input id="name" class="mui-navigate-right base_title_font base_black_grey name-input" type="text" placeholder="" onkeydown="return onKeyClick()">
            </div>
            <!-- <div class="head_div" >
                <span class="base_content_font base_dark_grey" >选择班级</span>
            </div>
            <div class="mui-input-row select-class-cell" onclick="selectClassClick()">
                <p id="select_class" class="select-class-title base_title_font base_black_grey"></p>
                <span class="stuname mui-navigate-right span_wight base_title_font base_black_grey" ></span>
            </div> -->
            <div class="head_div" >
                <span class="base_content_font base_dark_grey" >讨论描述</span>
            </div>
            <div class="mui-input-row" style="height: 160px" >
                <textarea id="content" class="textarea_t padding10 base_content_font base_black_grey  " maxlength="300" placeholder='描述本次讨论内容，最多输入300个字，可不填写' onkeyup="chagetext()"></textarea>
                <samp class="bottom_0_position base_content_font base_black_grey">还可以输入<em id="text_num">300</em>/300字</samp>
            </div>
            <div id="select_image_btn" class="head_div" style="height: 44px;padding: 10px;" >
                <em class="base_content_font base_black_grey add_pic_span">+ 添加图片</em>
            </div>
            <div id="select_image_div" class="selected-image" hidden="hidden">
                <img class="img-del" src="../../image/icon_img_del.png" onclick="deleteImageClick()" />
                <img src="../../image/course_placehoder.png" class="img_pic_style" id="img_pic" />
            </div>
        </form>
        <div id="picture" class="mui-popover mui-popover-action mui-popover-bottom">
            <ul class="mui-table-view">
                <li class="mui-table-view-cell">
                    <a href="#" typeid="0" style="color:#222;">拍照</a>
                </li>
                <li class="mui-table-view-cell">
                    <a href="#" typeid="1" style="color:#222;">从相册选取</a>
                </li>
            </ul>
            <ul class="mui-table-view">
                <li class="mui-table-view-cell">
                    <a href="#picture" typeid="2" style="color:#222;"><b>取消</b></a>
                </li>
            </ul>
        </div>
        <div id="offlineAlert" class="weui_dialog_confirm" style="display: none;">
            <div class="weui_mask"></div>
            <div class="weui_dialog">
                <div class="weui_dialog_hd">
                    <strong class="weui_dialog_title">是否确定退出当前页面？</strong>
                </div>
                <div class="weui_dialog_bd"></div>
                <div class="weui_dialog_ft">
                    <a onclick="cleanCancel()" href="#" class="weui_btn_dialog default">取消</a>
                    <a onclick="cleanConfirm()" href="#" class="weui_btn_dialog primary"  style="color:#18b4ed">确定</a>
                </div>
            </div>
        </div>
    </div>
    <div id="logout" class="weui_dialog_confirm" style="display: none;">
        <div class="weui_mask"></div>
        <div class="weui_dialog">
            <div class="weui_dialog_hd">
                <strong class="weui_dialog_title">是否确定开启此讨论？</strong>
            </div>
            <div class="weui_dialog_ft">
                <a onclick="cancel()" href="#" class="weui_btn_dialog default" style="color:#18b4ed">取消</a>
                <a onclick="confirm()" href="#" class="weui_btn_dialog primary" style="color:#18b4ed">确定</a>
            </div>
        </div>
    </div>
</body>
<script type="text/javascript" src="../../script/api.js"></script>
<script type="text/javascript" src="../../script/jquery.min.js"></script>
<script type="text/javascript" src="../../script/mui.min.js"></script>
<script type="text/javascript" src="../../script/common.js"></script>
<script type="text/javascript" src="../../script/MD5.js"></script>
<script type="text/javascript" src="../../script/processing_images.js"></script>
<script type="text/javascript" src="../../script/requestTool.js"></script>
<script type="text/javascript" src="../../script/timeStampTool.js"></script>
<script type="text/javascript">
    var classarr = [];
    var className = '';
    var classid = '';
    var imgPath = '';
    var currentId = '';
    var contentInitialValue = '';//内容初始值
    var imgInitialValue = '';//内容初始值
    var nameInitiValue = '';//标题初始值
	apiready = function(){
        prepareData();
	    setupNotifi();
        setSelectPicture();
        setupInput();
        if(api.pageParam.editType == 'add'){
            sendBuriedNotifi('0', '老师端讨论创建页', '207');
        }else{
            sendBuriedNotifi('0', '老师端讨论编辑页', '206');
        }
    }
    
	function sendBuriedNotifi(busionessid, pagetype, pagetypeid) {
		var userinfo = {
			uid : $api.getStorage('cfnetppuid'),
			jid : $api.getStorage('cfnetppjxid'),
			uname : $api.getStorage('cfnetppusername'),
			cid : api.pageParam.cid,
		    pid : api.pageParam.pid
		}
		var data = {
			busionessid : busionessid,
			pagetype : pagetype,
			pagetypeid : pagetypeid,
			sourceurl : api.pageParam.sourceurl,
			sourcetitle : api.pageParam.sourcetitle,
			accesspageurl : window.location.pathname,
			accesspagetitle : document.title,
			userinfo : userinfo
		}
		SendBehaviorTrajectoriesNotifi_Study(data);
	}
    function setupInput(){
        $('#name').bind('input propertychange', function() {  
            var currentName = $('#name').val();
            if (currentName.length > 20) {
                currentName = currentName.slice(0,20);
                $('#name').val(currentName);
                api.toast({
                    msg: '讨论名称最长20字'
                });
            }
        });
    }
    function prepareData(){
        var editType = api.pageParam.editType;
        if (editType == 'add') {
            showAddImageBtn();
            $('#pub_btn').text("完成");
            loadDisName();
        }else{
            loadDisDetail();
            currentId = api.pageParam.id;
        }
    }
    function loadDisName(){
        var param = {
            jid : $api.getStorage('cfnetppjxid')
        };
        cfnetppPOST(url_getZcode, param, false, function(data, status){
            if (status == "success") {
                if (data.code == 200) {
                    $('#name').val("讨论-"+data.zcode);
                }else{
                    $('#name').val("讨论-"+getNowDateYue());
                }
            }else{
                $('#name').val("讨论-"+getNowDateYue());
            }
            nameInitiValue = $('#name').val();//设置名称初始值
        });
    }
    function loadDisDetail() {
        var param = {
            id: api.pageParam.id,
            uid: $api.getStorage('cfnetppuid'),
            jid: $api.getStorage('cfnetppjxid')
        }
        cfnetppPOST(url_DiscussEdit, param, false, function(data, status){
            if (status == 'success') {
                if (data.code == 200) {
                    var disData = data.data[0];
                    if (disData != null) {
                        var name = disData.name;
                        $('#name').val(name);
                        nameInitiValue = $('#name').val();
                        var content = disData.content;
                        contentInitialValue = content;//编辑模式下的内容初始值
                        $('#content').val(content);
                        var upfile = disData.upfile;
                        if (upfile == null || upfile == '') {
                            showAddImageBtn();
                        }else{
                            $('#img_pic').attr('src', upfile);
                            imgPath = upfile;
                            imgInitialValue = upfile;
                            showImage();
                        }
                        var classlist = disData.classlist;
//                      setupClasslist(classlist);
                        chagetext();//更新当前字数
                    }
                }
            }
        });
    }
    function showImage(){
        $('#select_image_div').show();
        $('#select_image_btn').hide();
    }
    function showAddImageBtn() {
        $('#select_image_div').hide();
        $('#select_image_btn').show();
    }
    function deleteImageClick() {
        imgPath = '';
        showAddImageBtn();
    }
    function setSelectPicture(){
        $('#select_image_btn').click(function(){
            mui('#picture').popover('toggle');
        });
        mui('body').on('tap', '.mui-popover-action li>a', function() {
            var typeid = $(this).attr('typeid');
            if (typeid == 0) {//拍照
                mui('#picture').popover('toggle');
                api.getPicture({
                    sourceType : 'camera',
                    encodingType : 'jpg',
                    mediaValue : 'pic',
                    destinationType : 'url',
                    allowEdit : true,
                    quality : 50,
                    saveToPhotoAlbum : false
                }, function(ret, err) {
                    if (ret) {
                        var photoPath = ret.data;
                        if (photoPath != '') {
                            $('#img_pic').attr('src', photoPath);
                            showImage();
                            addpatrol(photoPath);
                        }
                    } else {
                        api.toast({
                            msg : JSON.stringify(err)
                        });
                    }
                });
            } else if (typeid == 1) {//从相册选择
                mui('#picture').popover('toggle');
                api.getPicture({
                    sourceType : 'album',
                    encodingType : 'jpg',
                    mediaValue : 'pic',
                    destinationType : 'url',
                    allowEdit : true,
                    quality : 50,
                    saveToPhotoAlbum : false
                }, function(ret, err) {
                    if (ret) {
                        var photoPath = ret.data;
                        if (photoPath != '') {
                            $('#img_pic').attr('src', photoPath);
                            showImage();
                            addpatrol(photoPath);
                        }
                    } else {
                        api.toast({
                            msg : JSON.stringify(err)
                        });
                    }
                });
            }
        });
    }
    //上传图片
    function addpatrol(compressImg) {
        api.showProgress({
            style: 'default',
            animationType: 'fade',
            title: '上传图片中...',
            text: '',
            modal: false
        });
        UploadFile_ali(Upload_File_img, compressImg, function(ret) {
            imgPath = ret.fileurl;
            hideProgress();
        });
    }
    //返回
    function backClick() {
        var cuCont = $('#content').val();
        var cuName = $('#name').val();
        // console.log('contentInitialValue:'+contentInitialValue+'\nimgPath:'+imgPath+'\ncontentInitialValue:'+contentInitialValue+'\ncuCont:'+cuCont);
        if (nameInitiValue == cuName && contentInitialValue == imgPath && contentInitialValue == cuCont) {
            cleanConfirm();
        }else{
            $('#offlineAlert').show();
        }
    }
    //取消
    function cleanCancel() {
        $('#offlineAlert').hide();
    }
    //确定
    function cleanConfirm() {
	    if(api.pageParam.editType == 'add'){
            sendBuriedNotifi('0', '老师端讨论创建页', '207');
        }else{
            sendBuriedNotifi('0', '老师端讨论编辑页', '206');
        }
        api.closeWin();
    }
    function cancel(){
        $('#logout').hide();
        api.closeWin();
    }
    function confirm(){
        startActity();
    }
    function onKeyClick() {
        if (event.keyCode == 13) {
            return false;
        }
    }
    //监听剩余字数
    function chagetext(){
        var num = 300 - $('#content').val().length;
        $('#text_num').html(num);
    }
    function saveClick(){
        var name = $('#name').val();
        if(name == '' || isOnlySpaceOrEnter(name)){
            ShowToast('请填写讨论名称');
            return;
        }
        var content = $('#content').val();
        // if (classid == '' || classid == null) {
        //     ShowToast('请选择班级');
        //     return;
        // }
        var params = {
            jid: $api.getStorage('cfnetppjxid'),
            uid: $api.getStorage('cfnetppuid'),
            tid: 4,
            // classid: classid,
            name: name,
            content: content,
            cid : api.pageParam.cid,
            pid : api.pageParam.pid,
            file: imgPath
        }
        var urlString = url_addActive;
        var editType = api.pageParam.editType;
        if (editType == 'add'){//添加
            urlString = url_addActive;
        }else{//修改
            urlString = url_DiscussUpdate;
            params = {
                id: api.pageParam.id,
                uid: $api.getStorage('cfnetppuid'),
                jid: $api.getStorage('cfnetppjxid'),
                // classid: classid,
                name: name,
                content: content,
                file: imgPath
            }
        }
        api.showProgress();
        cfnetppPOST(urlString, params, true, function(data, status) {
            api.hideProgress();
            if(editType == 'add'){
                SendBusinessOperationsLogNotifi('老师端讨论创建', '207', params, params, '', data, '老师端讨论创建接口  ', '207-01');
            }else{
                SendBusinessOperationsLogNotifi('老师端讨论编辑', '206', params, params, '', data, '老师端讨论编辑接口  ', '206-01');
            }
            if (status == 'success') {
                if (data.code == 200) {
                    api.sendEvent({
                        name: 'refreshDiscussListNotifi'
                    });
                    if (currentId == '') {
                        currentId = data.iid;
                    }
                    $('#logout').show();
                }else if(data.code == 110){
                    api.toast({
                        msg: '讨论名称已存在'
                    });
                }else{
                    ShowToast(data.message);
                }
            }else{
                ShowToast('网络请求失败');
            }
        })
    }
    function selectClassClick(){
        api.openWin({useWKWebView:true,
            name: 'select_class',
            url: '../Teacher_Classroom/select_class.html',
            pageParam: {
                data: classarr
            }
        });
    }
    function setupNotifi(){
        api.addEventListener({
            name: 'refreshClassData'
        }, function(ret, err) {
            var classlist = ret.value.data;
            setupClasslist(classlist);
        });
        api.addEventListener({
            name: 'keyback'
        }, function(ret, err) {
            backClick();
        });
    }
    function setupClasslist(classlist){
        // if (classlist != null && classlist.constructor == Array && classlist.length > 0) {
        classarr = classlist;
        className = '';
        classid = '';
        for (var i = 0; i < classarr.length; i++) {
            var classData = classarr[i];
            className = className + classData.name + ',';
            classid = classid + classData.id + ',';
        }
        className = className.slice(0, className.length - 1);
        classid = classid.slice(0, classid.length - 1);
        $('#select_class').text(className);
        // }else{
        //     $('#select_class').text('');
        // }
    }
    function startActity(){
        var action = 'start';
        api.showProgress({
            style: 'default',
            animationType: 'fade',
            title: '',
            text: '讨论开启中...',
            modal: false
        });
        var param = {
            iid : currentId,
            tid : 4,
            action : action 
        };
        cfnetppPOST(url_actionDosign, param, false, function(data, status){
           if(api.pageParam.usertype=='teacher'){
              SendBusinessOperationsLogNotifi('老师端讨论开启', '205', param, param, '', data, '老师端讨论开启接口 ', '205-01')  
           }
            api.hideProgress();
            if (status == 'success') {
                if (data.code == 200) {
                    api.toast({
                        msg: '操作成功'
                    });
                    api.sendEvent({
                        name: 'discussUpdateStatusNotifi',
                        extra: {
                            id: currentId, 
                            status: 1
                        }
                    });
                    openDisDetailPage();
                }else{
                    api.toast({
                        msg: '操作失败请重试！'
                    });
                }
            }else{
                api.toast({
                    msg: '网络异常请重试！'
                });
            }
        });
    }
    function openDisDetailPage(){
        var disData = new Object();
        disData["usertype"] = 'teacher';
        disData["activestatus"] = 1;
        disData["cid"] = api.pageParam.cid;
        disData["pid"] = api.pageParam.pid;
        disData["id"] = currentId;
        disData["name"] = $('#name').val();
        disData["opentype"] = 'notlist';//非列表进入
        api.openWin({useWKWebView:true,
            name: 'Discuss_TeacherDetailWin',
            url: 'Discuss_TeacherDetailWin.html',
            pageParam: disData,
            slidBackEnabled: false
        });
    }
</script>
</html>